import React from 'react';
import classNames from 'classnames';
import PropTypes from 'prop-types';

import './index.less';

class Switch extends React.Component {
    /**
     * 开关状态，默认选中
     *
     * checked: bool;
     */
    /**
     * 点击开关回调，
     *
     * onChange: () => {};
     */

    static defaultProps = {
        checked: true,
        type: 'switch'
    };
    static propTypes = {
        checked: PropTypes.bool,
        onChange: PropTypes.func
    };
    constructor(props) {
        super(props);
        this.state = {
            checked: this.props.checked
        };
    }

    checkedChange = (value, e) => {
        e.preventDefault();
        e.stopPropagation();
        this.props.onChange(!value);
    };

    componentWillReceiveProps({ checked }) {
        this.setState({ checked });
    }

    render() {
        const { checked } = this.state;
        const { color = '#4CD964', disabled } = this.props;
        const swichClass = classNames({
            'switch-main': true,
            'checked-true': checked,
            'checked-false': !checked,
            'disabled-cls': disabled
        });
        const sty = checked
            ? {
                  backgroundColor: color,
                  border: `2px solid ${color}`
              }
            : {};

        return (
            <div
                style={sty}
                className={swichClass}
                onClick={!disabled && this.checkedChange.bind(this, checked)}
            >
                <div className="switch-dot" />
            </div>
        );
    }
}

export default Switch;
